from Tkinter import *
import Tkinter
import tkMessageBox


import modules.aim.vars as vars
import modules.gui.jarvars as jarvars
import modules.aim.aimClient 
from modules.aim.flap import *
from modules.mainWindow import *
from modules.sendCommand import *

import modules.driver.dvars as dvars
import modules.driver.cm19aDriver as cm
import socket

global mw

def main():
    global mw
    root = Tk()

    mw = MainWindow(root) 
    if jarvars.State == []:
        mw.resetState()
    
    dvars.cm19a = cm.configure()
    if(dvars.cm19a.initialised):
        mw.status.USBstatus.set("USB Controlling")
    else:
        mw.status.USBstatus.set("USB Not Controlling")
    
    
    while(1):
        response = ""
        if vars.connected:
            try:     
                r = flap()
                modules.aim.aimClient.get(vars.stream, r)
                if(r.SNAC.family == 4 and r.SNAC.subtype == 7):
                    parseAimCommand(r)                   
            except:
                pass
        try:
            web_socket
        except:
            pass
        mw.update()
        
def parseAimCommand(r):
    global mw
    print "In Parse"
    rec = r.SNAC.important.split(':', 1)
    print "Recieved", rec
    if rec[0] in jarvars.AuthorizedAimUsers:
        print "Authorized user", rec[0]
        message = rec[1].split(' ')
        print "Message", message
        if len(message) == 0:
            response = "invalid length"

        elif message[0][0] == '+':

            print "Direct command", message[0]
            processCommand(message[0], True)
            response = "Sent to X10: "+message[0]
        elif message[0][0] == '-':
            processCommand(message[0], False)
            response = "Sent to X10: "+message[0]
        elif len(message) < 2:
            response = "invalid command"
            
        else:
            light = message[0]
            command = message[1]
            if command.lower() == "on":
                                #X10Send('+'+light)
                print "Turn on light"
                processCommand('+'+light, True)
                response = "command to X10: +"+light
            elif command.lower() == "off":
                                #X10Send('-'+light)
                print "Turn off light"
                processCommand('-'+light, True)
                response = "command to X10: -"+light
                print "Turn off light", light
            else:
                response = "Command : "+ message+" was not understood"
        f = flap()
        f.SNAC.sendMessage(rec[0], response)
        aim.send(vars.stream, f)
    else: 
        print "Ingoring user ", rec[0]

def processCommand(command, on=None):
    global mw
    print command

    light = command[1:len(command)]
    light = str(light[0])+str(light[1])
    
    print light
    for jj in jarvars.State:
        for kk in range(len(jj[1])):
            if jj[1][kk][0] == light:
                if jj[1][kk][2] == 'Yes':
                    if jj[1][kk][1] == 'Yes':
                        if not on:
                            success, message = sendCommand(command)
                            if(success):
                                jj[1][kk][1] = 'No'
                                jarvars.numLightsOn -= 1
                                if jarvars.numLightsOn == 0:
                                    jarvars.LightsOn = False
                                mw.postToHistory(message)
                    else:
                        if on:
                            success, message = sendCommand(command)
                            if success:
                                jj[1][kk][1] = 'Yes'
                                jarvars.numLightsOn += 1
                                jarvars.LightsOn = True
                                mw.postToHistory(message)
    mw.updateStateList()
    
    
                
if __name__ == "__main__":
    

    main()

    


